package com.yf.course.modules.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.api.exception.ServiceException;
import com.yf.course.modules.course.dto.CourseRefFileDTO;
import com.yf.course.modules.course.entity.CourseRefFile;
import com.yf.course.modules.course.mapper.CourseRefFileMapper;
import com.yf.course.modules.course.service.CourseRefFileService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
* <p>
* 课程文件索引业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2021-03-12 16:18
*/
@Service
public class CourseRefFileServiceImpl extends ServiceImpl<CourseRefFileMapper, CourseRefFile> implements CourseRefFileService {

    @Override
    public void save(String courseId, List<CourseRefFile> list) {

        QueryWrapper<CourseRefFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseRefFile::getCourseId, courseId);
        this.remove(wrapper);

        if(CollectionUtils.isEmpty(list)){
            return;
        }

        try {
            this.saveBatch(list);
        }catch (DuplicateKeyException e){
            throw new ServiceException("不能加入重复的课件！");
        }

    }

    @Override
    public CourseRefFile findOne(String courseId, String fileId) {
        QueryWrapper<CourseRefFile> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(CourseRefFile::getCourseId, courseId)
                .eq(CourseRefFile::getFileId, fileId);

        return this.getOne(wrapper, false);
    }


    @Override
    public Integer countByCourse(String courseId) {
        //查询条件
        QueryWrapper<CourseRefFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CourseRefFile::getCourseId, courseId);
        return this.count(wrapper);
    }

    @Override
    public boolean checkFile(CourseRefFileDTO reqDTO) {

        QueryWrapper<CourseRefFile> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(CourseRefFile::getCourseId, reqDTO.getCourseId())
                .eq(CourseRefFile::getFileId, reqDTO.getFileId());

        return this.count(wrapper) > 0;
    }

    @Override
    public String findNextFile(String courseId, Integer sort) {

        // 解锁下一个
        QueryWrapper<CourseRefFile> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .select(CourseRefFile::getFileId)
                .eq(CourseRefFile::getCourseId, courseId)
                // 下一个+1
                .eq(CourseRefFile::getSort, sort+1);

        CourseRefFile next = this.getOne(wrapper, false);
        if(next!=null){
            return next.getFileId();
        }

        return null;
    }
}
